﻿#include "klbge2d.h"
#include "klbmem/klb_mem.h"


/// @brief 创建一个ge2d对象
klbge2d_t* klbge2d_create()
{
    klbge2d_t* p_ge2d = KLB_MALLOCZ(klbge2d_t, 1, 0);

    p_ge2d->p_world = world_create();
    p_ge2d->p_images = wsdl_images_create();

    return p_ge2d;
}

/// @brief 销毁ge2d对象
void klbge2d_destroy(klbge2d_t* p_ge2d)
{
    KLB_FREE_BY(p_ge2d->p_images, wsdl_images_destroy);

    KLB_FREE_BY(p_ge2d->p_world, world_destroy);
    KLB_FREE(p_ge2d);
}


int klbge2d_init(klbge2d_t* p_ge2d, int w, int h, const char* p_title)
{
    p_ge2d->p_wnd = sdl_window_create(w, h, p_title);

    wsdl_images_load(p_ge2d->p_images, p_ge2d->p_wnd->p_render, "aaa", "./ge2dres/images/background.bmp");
    wsdl_images_load(p_ge2d->p_images, p_ge2d->p_wnd->p_render, "bbb", "./ge2dres/images/background2.bmp");

    return 0;
}

void klbge2d_quit(klbge2d_t* p_ge2d)
{
    KLB_FREE_BY(p_ge2d->p_wnd, sdl_window_destroy);
}

world_t* klbge2d_get_world(klbge2d_t* p_ge2d)
{
    return p_ge2d->p_world;
}

static void klbge2d_render_once(klbge2d_t* p_ge2d)
{
    SDL_Renderer* p_render = p_ge2d->p_wnd->p_render;

    SDL_SetRenderTarget(p_render, NULL);

    SDL_SetRenderDrawColor(p_render, 10, 10, 10, 255);
    SDL_RenderClear(p_render);

    SDL_Texture* p_tex = wsdl_images_find(p_ge2d->p_images, p_render, "bbb");
    if (NULL != p_tex)
    {
        SDL_RenderCopy(p_render, p_tex, NULL, NULL);
    }

    SDL_RenderPresent(p_render);
}

int klbge2d_loop_once(klbge2d_t* p_ge2d, int64_t last_tc, int64_t now)
{
    if (NULL == p_ge2d->p_wnd)
    {
        return 0;
    }

    int done = 0;

    SDL_Event event;
    while (SDL_PollEvent(&event) > 0)
    {
        if (event.type == SDL_QUIT)
        {
            done = 1;
        }

        if (event.type == SDL_KEYDOWN)
        {
            if (event.key.keysym.sym == SDLK_ESCAPE)
            {
                //done = 1;
            }
        }

        if (SDL_WINDOWEVENT == event.type)
        {
            if (SDL_WINDOWEVENT_EXPOSED == event.window.event)
            {
                sdl_window_present(p_ge2d->p_wnd);
            }
        }
    }

    if (0 != done)
    {
        return 1;
    }

    if (20 <= ABS_SUB(now, p_ge2d->last_tc))
    {
        klbge2d_render_once(p_ge2d);
        p_ge2d->last_tc = now;
    }

    return 0;
}
